package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class CampaignController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def springSecurityService
    def exportService
    def subscribeService

    def index(Integer max)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def campaignList = Campaign.findAll("from Campaign where user.username = '${username}'", [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = Campaign.executeQuery("select count(id) from Campaign where user.username = '${username}'")

        respond campaignList, model: [campaignCount: count[0]]
    }

    def show(Campaign campaign)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def user = User.findByUsername(username)
        def noteList = Note.findAll("from Note where campaign.id = ?", [campaign.id])
        def attachmentList = Attachment.findAll("from Attachment where campaign.id = ?", [campaign.id])
        def appointmentList = Activity.findAll("from Activity where campaign.id = ? and type.id = ?", [campaign.id, ActivityType.find("from ActivityType where name = 'Appointment'")?.id])
        def taskList = Activity.findAll("from Activity where campaign.id = ? and type.id = ?", [campaign.id, ActivityType.find("from ActivityType where name = 'Task'")?.id])
        def teamList = CampaignTeam.findAll("from CampaignTeam where campaign.id = ?", [campaign.id])
        def flexFieldInstanceList = FlexFieldInstance.findAll("from FlexFieldInstance where campaign.id = ?", [campaign.id])
        def follow = Follow.findByCampaignAndUser(campaign, user)
        respond campaign, model: [noteList: noteList, attachmentList: attachmentList, appointmentList: appointmentList, taskList: taskList, teamList: teamList, flexFieldInstanceList: flexFieldInstanceList, teamName: 'campaignTeam', follow: follow]
    }

    def create()
    {
        respond new Campaign(params)
    }

    @Transactional
    def save(Campaign campaign)
    {
        if (campaign == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (campaign.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond campaign.errors, view: 'create'
            return
        }
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        campaign.createBy = user
        campaign.modifyBy = user
        campaign.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'campaign.label', default: 'Campaign'), campaign.id])
                redirect campaign
            }
            '*' { respond campaign, [status: CREATED] }
        }
    }

    def edit(Campaign campaign)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        TeamRole editTeamRole = TeamRole.findByName('Edit')
        CampaignTeam campaignTeam = CampaignTeam.findByCampaignAndUser(campaign, user)

        if (campaign?.user?.id == user?.id || campaignTeam?.teamRole?.id == editTeamRole?.id)
        {
            respond campaign
        }
        else
        {
            flash.message = "没有编辑权限"
            respond campaign, view: 'show'
        }
    }

    @Transactional
    def update(Campaign campaign)
    {
        if (campaign == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (campaign.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond campaign.errors, view: 'edit'
            return
        }
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        campaign.modifyBy = user
        campaign.save flush: true
        subscribeService.sendSubscribe campaign

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'campaign.label', default: 'Campaign'), campaign.id])
                redirect campaign
            }
            '*' { respond campaign, [status: OK] }
        }
    }

    @Transactional
    def delete(Campaign campaign)
    {

        if (campaign == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        campaign.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'campaign.label', default: 'Campaign'), campaign.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'campaign.label', default: 'Campaign'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def searchCampaign()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def name = params["name"]
        def type = params["type"]

        String sql = "from Campaign as u where 1=1 and u.user.username = '${username}'"
        if (name)
        {
            sql += " and u.name like '%${name}%'"
        }
        if (type)
        {
            sql += " and u.type.name like '%${type}%'"
        }
        String countSql = "select count(u.id) " + sql
        sql += ' order by createdDate desc'

        def list = Campaign.findAll(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = Campaign.executeQuery(countSql)

        respond list, model: [campaignCount: count[0], params: params], view: 'index'
    }

    def exportCampaign()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def name = params["name"]
        def type = params["type"]

        String sql = "from Campaign as u where 1=1 and u.user.username = '${username}'"
        if (name)
        {
            sql += " and u.name like '%${name}%'"
        }
        if (type)
        {
            sql += " and u.type.name like '%${type}%'"
        }
        String countSql = "select count(u.id) " + sql
        sql += ' order by createdDate desc'

        def list = Campaign.findAll(sql)
        def count = Campaign.executeQuery(countSql)

        if (params?.f && params.f != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.f]
            response.setHeader("Content-disposition", "attachment; filename=campaign.${params.extension}")
            List fields = ["name", "status.name", "parent.name", "type.name", "territory.name", "startTime", "endTime", "description", "active", "createdDate", "modifiedDate"]
            Map labels = ["name": "名称", "status.name": "状态", "parent.name": "父级市场活动", "type.name": "类型", "territory.name": "区域", "startTime": "开始时间", "endTime": "结束时间", "description": "描述", "active": "启用", "createdDate": "创建时间", "modifiedDate": "修改时间"]
            exportService.export(params.f, response.outputStream, list, fields, labels, [:], [:])
        }
    }
}
